var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// 导入
const session = require("express-session");
const FileStore = require('session-file-store')(session);

// 创建 session 中间件
const sessionMiddleware = session({
    store: new FileStore(),
    secret: 'fdsfdsf fdssdf',
    cookie: { maxAge: 60000 }
});

var server = require("http").Server(app);
var io = require('socket.io')(server);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(sessionMiddleware);

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});



server.listen(3000, function() {
    console.log('listening on *:3000');

});

var users = []; // 储存登录用户
var usersInfo = []; // 存储用户姓名和头像
// 每个连接的用户都有专有的socket
/* 
   io.emit(foo); //会触发所有用户的foo事件
   socket.emit(foo); //只触发当前用户的foo事件
   socket.broadcast.emit(foo); //触发除了当前用户的其他用户的foo事件
*/
// 用户连接时触发
io.on('connection', (socket) => {
    console.log('a user connected');
    // 渲染在线人员
    io.emit('disUser', usersInfo);
    // 登录，检测用户名
    socket.on('login', (user) => {
        console.log('user ' + user.name);
        console.log(users);


        if (users.indexOf(user.name) > -1) {
            socket.emit('loginError');
        } else {
            users.push(user.name);
            usersInfo.push(user);
            socket.nickname = user.name;
            console.log("socket " + socket.nickname);

            // io.emit('system', {
            //     name: user.name,
            //     status: '进入'
            // });
            io.emit('disUser', usersInfo);
            console.log(users.length + ' user connect.');
        }
    });
    // 发送消息
    socket.on('sendMsg', (data) => {
        var img = '';
        console.log("发送消息" + data.name);

        for (var i = 0; i < usersInfo.length; i++) {
            console.log(usersInfo[i].name + " " + socket.nickname);

            if (usersInfo[i].name == data.name) {
                img = usersInfo[i].img;
                console.log("img " + img);

            }
        }
        socket.broadcast.emit('receiveMsg', {
            name: data.name,
            img: img,
            msg: data.msg,
            color: data.color,
            type: data.type,
            date: new Date().format('yyyy-MM-dd hh:mm:ss'),
            side: 'left'
        });
        socket.emit('receiveMsg', {
            name: data.name,
            img: img,
            msg: data.msg,
            color: data.color,
            type: data.type,
            date: new Date().format('yyyy-MM-dd hh:mm:ss'),
            side: 'right'
        });
    });
});

Date.prototype.format = function(format) {
        var o = {
            "M+": this.getMonth() + 1, //month
            "d+": this.getDate(), //day
            "h+": this.getHours(), //hour
            "m+": this.getMinutes(), //minute
            "s+": this.getSeconds(), //second
            "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
            "S": this.getMilliseconds() //millisecond
        }
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
            (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(format))
                format = format.replace(RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] :
                    ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    }
    // module.exports = app;